package com.vf.cloud.pass.mvc.biz.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.jfinal.kit.StrKit;
import com.vf.cloud.pass.common.domain.biz.Scene;
import com.vf.cloud.pass.common.domain.biz.Terminal;
import com.vf.cloud.pass.common.domain.biz.TerminalScene;

@Controller
public class DownLoadController {
	private final static String utf8 = "utf-8";

	@RequestMapping("/down")
	public void downLoadFile(HttpServletRequest request, HttpServletResponse response) {

		response.setCharacterEncoding(utf8);
		// 定义文件路径
		InputStream is = null;
		OutputStream os = null;
		try {

			String terminalId = request.getHeader("terminalId");
			String sceneId = request.getHeader("sceneId");
			String complete = request.getHeader("complete");

			if (StrKit.isBlank(terminalId) || StrKit.isBlank(sceneId)) {
				throw new Exception("参数必填!");
			}

			
			Terminal terminal = Terminal.dao.findById(terminalId);
			if (terminal == null) {

				throw new Exception("无效客户端ID!");
			}

			Scene scene = Scene.dao.findById(sceneId);
			if (scene == null) {
				throw new Exception("场景不存在，请联系管理员!");
			}

			File file = new File(scene.getZipFile());
			if (!file.exists()) {
				throw new Exception("场景不存在，请联系管理员!");
			}

			TerminalScene terminalProject = TerminalScene.dao.findByIds(terminalId,sceneId);
			if (terminalProject == null) {
				terminalProject = new TerminalScene();
				terminalProject.setTerminalId(terminalId);
				terminalProject.setSceneId(sceneId);
				terminalProject.setVersion(scene.getVersion());
				terminalProject.setDownLoadStatus("1");
				terminalProject.setExeFilePath(String.format("%s/%s",scene.getId(), scene.getExeFilePath()));
				terminalProject.setFileLength(file.length() + "");
				terminalProject.save();
			}
			
			
			if (!StrKit.isBlank(complete)) {
				if (StrKit.equals("Decompression_Completed", complete)) {
					terminalProject.setDownLoadStatus("3");
					terminalProject.update();
					throw new Exception("Decompression_Completed.");
				}
			}
			
			terminalProject.setExeFilePath(String.format("%s/%s",scene.getId(), scene.getExeFilePath()));
			terminalProject.setVersion(scene.getVersion());
			terminalProject.setDownLoadStatus("1");
			terminalProject.update();

			// 分片下载
			long fSize = file.length();// 获取长度
			response.setContentType("application/x-download");
			String fileName = URLEncoder.encode(file.getName(), utf8);
			response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
			// 根据前端传来的Range 判断支不支持分片下载
			response.setHeader("Accept-Range", "bytes");
			// 获取文件大小
			response.setHeader("fSize", String.valueOf(fSize));
			response.setHeader("fName", fileName);

			// 定义断点
			long pos = 0, last = fSize - 1, sum = 0;
			// 判断前端需不需要分片下载
			if (null != request.getHeader("Range")) {
				response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
				String numRange = request.getHeader("Range").replaceAll("bytes=", "");
				String[] strRange = numRange.split("-");
				if (strRange.length == 2) {
					pos = Long.parseLong(strRange[0].trim());
					last = Long.parseLong(strRange[1].trim());
					// 若结束字节超出文件大小 取文件大小
					if (last > fSize - 1) {
						last = fSize - 1;
					}
				} else {
					// 若只给一个长度 开始位置一直到结束
					pos = Long.parseLong(numRange.replaceAll("-", "").trim());
				}
			}

			long rangeLenght = last - pos + 1;
			String contentRange = new StringBuffer("bytes").append(pos).append("-").append(last).append("/")
					.append(fSize).toString();
			response.setHeader("Content-Range", contentRange);
			response.setHeader("Content-Lenght", String.valueOf(rangeLenght));
			os = new BufferedOutputStream(response.getOutputStream());
			is = new BufferedInputStream(new FileInputStream(file));
			is.skip(pos);// 跳过已读的文件
			byte[] buffer = new byte[1024];
			int lenght = 0;
			// 相等证明读完
			while (sum < rangeLenght) {
				lenght = is.read(buffer, 0,
						(rangeLenght - sum) <= buffer.length ? (int) (rangeLenght - sum) : buffer.length);
				sum = sum + lenght;
				os.write(buffer, 0, lenght);

			}
			
			terminalProject.setDownLoadStatus("2");
			terminalProject.update();
			
		} catch (Exception e) {
			try {
				response.setHeader("message", URLEncoder.encode(e.getMessage(), utf8));
			} catch (UnsupportedEncodingException e1) {
			}
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (os != null) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}